﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StateMachineCompiler
{
	public class Controller
	{
		private State currentState;
		private StateMachine machine;
		private CommandChannel commandChannel;

		public CommandChannel CommandChannel { get { return this.commandChannel; } }

        public State CurrentState { get { return this.currentState; } }

		public Controller(StateMachine machine, CommandChannel commandChannel)
		{
			this.machine = machine;
			this.commandChannel = commandChannel;
            this.currentState = machine.Start;
		}

		public void Handle(string eventCode)
		{
			if (currentState.HasTransition(eventCode))
				TransitionTo(currentState.GetTargetState(eventCode));
			else if (machine.IsResetEvent(eventCode))
				TransitionTo(machine.Start);
		}


		private void TransitionTo(State target)
		{
			currentState = target;
			currentState.ExecuteActions(commandChannel);
		}
	}
}
